<template>
  <section class="chat-page-wrap">
    <div class="chat-popup-wrap">
      <Header></Header>
      <div class="container">
        <div class="content">
          <div class="scroll-content" ref="scrollRef" :style="{scrollBehavior: initLock ? 'smooth' : 'unset'}">
            <ul>
              <li v-for="(item, ii) in chatStore.message" :key="ii">
                <ModelChat v-if="item.flag === 'model'" :row="item"></ModelChat>
                <UserChat v-if="item.flag === 'user'" :loading="sendLock" :row="item"></UserChat>
              </li>
            </ul>
          </div>
          <Footer @send="send" :sendLock="sendLock"></Footer>
        </div>
        <Aside @send="send" :sendLock="sendLock" :problem="problem"></Aside>
      </div>
    </div>
    <div class="copyright">
      西安热工院提供服务支持
    </div>
  </section>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import { useChatStore } from "@/store";

import Header from './components/header.vue';
import Footer from './components/footer.vue';
import Aside from './components/aside.vue';

import ModelChat from "./components/ModelChat.vue";
import UserChat from "./components/UserChat.vue";

onMounted(() => {
  initProblem();
  scrollToBottom();
  nextTick(() => {
    initLock.value = true;
  });
});

const initLock = ref(false);
const sendLock = ref(false);

const chatStore = useChatStore();

const scrollRef = ref();
const scrollToBottom = () => {
  if (scrollRef.value) {
    scrollRef.value.scrollTop = scrollRef.value.scrollHeight;
  }
}

const send = async (search: string) => {
  if (sendLock.value) return ElMessage.warning("等待响应结果");
  sendLock.value = true;
  ElMessage.success("发送成功");
  const data = JSON.stringify({
    query: search || "请介绍一下在光伏电站建设中有哪些安全方面管理要求",
    knowledge_base_name: "tpri_kb",
  });

  chatStore.addMessage({
    flag: "user",
    message: [
      { answer: search, }
    ],
  });
  nextTick(() => {
    scrollToBottom();
  });

  const res = await fetch("/api/chat/knowledge_base_chat", {
    method: "POST",
    headers: {
      'Content-Type': 'application/json',
    },
    body: data,
  });

  const reader = res.body?.pipeThrough(new TextDecoderStream()).getReader();
  const result: ChatType[] = [];
  while(true) {
    const read = await reader?.read();
    if (read?.done) break;
    const row = JSON.parse(read?.value.replace("data:", "") as string) as ChatType;
    result.push(row);
  }

  chatStore.addMessage({
    flag: "model",
    message: result,
  });
  nextTick(() => {
    scrollToBottom();
  });

  sendLock.value = false;
}

const problem = ref<string[]>([]);
const initProblem = async () => {
  const res = await fetch("/data/problem.json");
  const rows =  await res.json();
  problem.value = rows;
}
</script>

<style lang="scss" scoped>
@import "@/assets/scss/pages/chat.scss";
</style>